package com.example.netty.netty.codec2;

import com.example.netty.netty.codec.StudentPOJO;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

//需要继承一个HandlerAdapter（有很多个）
public class NettyServerHandler extends SimpleChannelInboundHandler<MyDataInfo.MyMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.MyMessage myMessage) throws Exception {
        if (myMessage.getDataType()== MyDataInfo.MyMessage.DataType.StudentType) {
            System.out.println(myMessage.getStudent().getId()+" "+myMessage.getStudent().getName());
        } else if (myMessage.getDataType() == MyDataInfo.MyMessage.DataType.WorkerType) {
            System.out.println(myMessage.getWorder().getName()+" "+myMessage.getWorder().getAge());
        } else {
            System.out.println("传输的类型不正确");
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //读取完成后触发，一般用于数据返回
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,client...",CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //发生异常时触发，一般要关闭通道
        ctx.close();
    }
}
